package com.example.netty.nio.buffer;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

public class BufferDemo {
    public static void decode(String str) throws UnsupportedEncodingException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(128);//设置初始容量  开辟buffer
        byteBuffer.put(str.getBytes("utf-8"));   //放数据

        byteBuffer.flip();//反转

        //获取utf'-8解码器
        Charset charset = Charset.forName("utf-8");
        //对byteBuffer中的内容进行解码
        CharBuffer dharBuffer = charset.decode(byteBuffer);

        /*
        * array（）返回的就是内部的数组引用 ，编码以后 有效长度 0-limit  decode.limit()
        *
        * */
        char[] chars = Arrays.copyOf(dharBuffer.array(), dharBuffer.limit());
        System.out.println(chars);


    }


    public static void encode(String str) throws UnsupportedEncodingException {
        CharBuffer charBuffer = CharBuffer.allocate(128);//设置初始容量  开辟buffer
        CharBuffer append = charBuffer.append(str);
        charBuffer.flip();//反转

        //获取utf'-8解码器
        Charset charset = Charset.forName("utf-8");
        //对byteBuffer中的内容进行解码
        ByteBuffer byteBuffer = charset.encode(charBuffer);

        /*
        * array（）返回的就是内部的数组引用 ，编码以后 有效长度 0-limit  decode.limit()
        *
        * */
        byte[] bytes = Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());
        System.out.println(Arrays.toString(bytes));


    }

    public static void main(String[] args) {
        try {
            BufferDemo.decode("吴登庭");
            BufferDemo.encode("吴登庭");//
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
